#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include "../Sock/Socket.hpp"
#include "../Sock/errno.hpp"
#include "../Sock/Logmessage.hpp"
#include <sstream>
#include <fstream>
#include <memory>
namespace ftpServer
{
    using namespace std;
    static const uint16_t gport=8080;
    
    class Server
    {
        uint16_t  port_;
        int listen_fd_;
    public:
        Server(const uint16_t port=gport)
            :listen_fd_(-1),port_(port)
        {}    
        void init()
        {
           
            listen_fd_=Socket::CreateSock();
            Socket::Setsockopt(listen_fd_);
            Socket::Bind(listen_fd_,port_);
            Socket::Listen(listen_fd_);
        }

        void run()
        {
            for(;;)
            {
                std::string clientip;
                uint16_t clientport=0;
                int sock=Socket::Accept(listen_fd_,&clientip,&clientport);
                if(sock<0)
                {
                    logMessage(WARNING,"accept err...");
                    continue;
                }
                logMessage(NORMAL,"accept sock [%d] success...",sock);

                serverIO(sock);
                close(sock);
            }

        }
        ~Server(){}

    private:
        void serverIO(int sock)
        {
            char  filename[50];
            while (true)
            {
                ssize_t n=recv(sock,filename,sizeof(filename)-1,0);
                if(n>0)
                {
                    //构造Server端文件路径
                    filename[n]=0;
                    cout<<filename<<endl;
                    string filePath="ServerRoot/";
                    filePath+=filename;
                    //读取文件内容
                    std::ifstream in(filePath,std::ios_base::binary);
                    if(!in)
                    {
                        logMessage(ERROR,"download File err");
                        break;
                    }
                    std::ostringstream oss;  // 创建字符串流缓冲区  
                    oss << in.rdbuf();  // 将文件流连接到的字符串流缓冲区中  
                    std::string buffer = oss.str();  // 将缓冲区中的内容保存到字符串中 

                    cout<<buffer<<endl;
                    send(sock,buffer.c_str(),buffer.size(),0);
                    in.close();
                }
                else if(n==0)
                {
                    logMessage(NORMAL,"client quit and I also quit");
                    break;
                }
            }
        }
        
    };
}